using UnityEngine;

namespace DL.Movement
{
    /// <summary>
    /// 地面检测器
    /// 这里使用CapsuleCollider是为了方便以后将CC变为刚体组件驱动位移
    /// </summary>
    [RequireComponent(typeof(CapsuleCollider))]
    public class OnGroundedSensor : MonoBehaviour
    {
        [SerializeField]
        protected CapsuleCollider CapsuleCollider;
        [SerializeField]
        protected LayerMask Obs;
        protected float Offset = 0.1f;
        
        private bool m_Init;
        private float m_Radius;
        private Vector3 m_Top;
        private Vector3 m_Buttom;
        private Transform m_Obj; //对象
        private Collider[] m_Result;
        private int m_Count;
        
        [field: SerializeField] public bool IsGrounded { get; set; }

        private void Awake()
        {
            m_Init = false;
            m_Obj = transform;
            CapsuleCollider = GetComponent<CapsuleCollider>();
            if (CapsuleCollider == null)
            {
                Debug.LogError("未获取到对象胶囊体，地面检测将失效！");
            }
            else
            {
                m_Radius = CapsuleCollider.radius;
                m_Result = new Collider[32];
                m_Init = true;
            }
        }

        private void FixedUpdate()
        {
            if (!m_Init) return;
            var position = m_Obj.position;
            var up = m_Obj.up;
            m_Buttom = position + up * (m_Radius - Offset);
            m_Top = position + up * (CapsuleCollider.height - m_Radius - Offset);
            
            m_Count = Physics.OverlapCapsuleNonAlloc(m_Buttom, m_Top, m_Radius, m_Result, Obs,QueryTriggerInteraction.Ignore);
            
            if (m_Count > 0)
            {
                IsGrounded = true;
            }
            else
            {
                IsGrounded = false;
            }
        }
        
        public bool GetIsGrounded()
        {
            return IsGrounded;
        }

    }
}
